package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.manager.mapper.SysUserRoleMapper;
import com.atguigu.spzx.manager.service.SysUserRoleService;
import com.atguigu.spzx.model.pojo.system.SysRole;
import com.atguigu.spzx.model.pojo.system.SysUserRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /*
     * @description: 根据用户id获取角色信息
     **/
    @Override
    public List<SysRole> getRolesByUserId(Long id) {
        return sysUserRoleMapper.getRolesByUserId(id);
    }

    /*
     * @description: 分配用户角色
     **/
    @Override
    public boolean assignUserRole(Long userId, List<Long> roleIds) {
        //TODO 2025/1/1 要考虑分配的角色id是否合法
//        1、删除用户所有对应的角色
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        sysUserRoleMapper.delete(wrapper);
//        2、 添加角色
        for (Long roleId : roleIds) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        }
        return true;
    }
}
